package com.example.testdemoutils.openAI;


import com.alibaba.fastjson2.JSONObject;
import lombok.experimental.UtilityClass;
import okhttp3.*;

import java.io.IOException;
import java.util.Scanner;

/**
 * @author Astar
 * ClassName:OpenAIAPI.java
 * date:2023-03-03 16:49
 * Description:
 */
@UtilityClass
public class OpenAIAPI {
    /**
     * 聊天端点
     */
    final String chatEndpoint = "https://one.aiskt.com/v1/chat/completions";
    /**
     * api密匙
     */
    final String apiKey = "sk-5p0w1PEdb2fnJVUoE0636702204b4aC0Bc497aEc9e525b4f";

    public static final MediaType JSON = MediaType.parse("application/json");

    /**
     * 发送消息
     *
     * @param txt 内容
     * @return {@link String}
     */
    public String chat(String txt) {

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON, "{\n"
                + "    \"model\": \"gpt-3.5-turbo\",\n"
                + "    \"messages\": [\n"
                + "        {\n"
                + "            \"role\": \"user\",\n"
                + "            \"content\": \"" + txt + "\"\n"
                + "        }\n"
                + "    ],\n"
                + "    \"temperature\": 0.5,\n"
                + "    \"max_tokens\": 150,\n"
                + "    \"top_p\": 1,\n"
                + "    \"frequency_penalty\": 0.0,\n"
                + "    \"presence_penalty\": 0.0\n"
                + "}");

        Request request = new Request.Builder()
                .url(chatEndpoint)
                .header("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 打印响应体或进行其他处理
            String string = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(string);
            JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
            return choices.getJSONObject("message").getString("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input;
        while (true) {
            input = scanner.nextLine(); // 读取用户输入的一行文本
            // 检查是否输入了退出命令
            if ("退出".equalsIgnoreCase(input)) {
                System.out.println("对话结束，感谢你的使用！");
                break; // 退出循环
            }
            System.out.println(chat(scanner.next()));
        }
        scanner.close();
    }
}

